import { injectable, inject } from 'tsyringe';
import { WebSocketEvents } from '../../domain/types';
import type { IChatService } from '../../domain/interfaces/IChatService';
import type { IWebSocketManager } from '../../domain/interfaces/IWebSocketManager';
import { LoggerToken } from '../../domain/interfaces/ILogger';
import type { ILogger } from '../../domain/interfaces/ILogger';
import { validateChatMessage } from '../../utils/validation';
import { WebSocketHandler } from '../../core/websocketHandler';

@injectable()
export class ChatHandlers {
  constructor(
    @inject('IChatService') private chatService: IChatService,
    @inject('IWebSocketManager') private wsManager: IWebSocketManager,
    @inject(LoggerToken) private logger: ILogger
  ) {}

  async handleChatMessage(ws: any, data: unknown, requestId?: string) {
    try {
      const validatedData = validateChatMessage(data as any);
      
      await this.chatService.sendMessage(validatedData.roomId, {
        ...validatedData,
        id: this.generateMessageId(),
        status: 'delivered'
      });

      this.logger.info('Message processed', {
        roomId: validatedData.roomId,
        userId: validatedData.userId
      });

      WebSocketHandler.sendMessage(ws, {
        event: WebSocketEvents.CHAT_MESSAGE,
        data: { status: 'sent', messageId: validatedData.id },
        requestId,
        timestamp: Date.now()
      });

    } catch (error) {
      this.logger.error('Failed to process chat message', error as Error);
      
      WebSocketHandler.sendMessage(ws, {
        event: WebSocketEvents.ERROR,
        error: 'Failed to send message',
        requestId,
        timestamp: Date.now()
      });
    }
  }

  async handleJoinRoom(ws: any, data: any) {
    // 简化实现
    const { roomId, user } = data || {};
    await this.chatService.joinRoom(roomId, user);
  }

  private generateMessageId(): string {
    return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}
